from flask import request
from flask_login import login_required
from api.db.services.registerInvitation_service import RegisterInvitationService
from api.utils.api_utils import get_json_result

@manager.route("/invite-codes/create", methods=["POST"])
@login_required
def create_invite_code():
    """创建邀请码（纯POST方式）"""
    data = request.json
    creator_email = data.get("creator_email")
    
    if not creator_email:
        return get_json_result(
            data=False,
            message="Creator email is required",
            code=400
        )
    
    invite_code = RegisterInvitationService.create_invite_code(creator_email)
    if not invite_code:
        return get_json_result(
            data=False,
            message="Failed to create invite code",
            code=500
        )
    
    return get_json_result(data={
        "id": invite_code.id,
        "code": invite_code.code,
        "creator_email": invite_code.creator_email,
        "create_time": invite_code.create_time
    })

@manager.route("/invite-codes/revoke", methods=["POST"])
@login_required
def revoke_invite_code():
    """作废邀请码（纯POST方式）"""
    data = request.json
    code_id = data.get("code_id")
    
    if not code_id:
        return get_json_result(
            data=False,
            message="Code ID is required",
            code=400
        )
    
    success = RegisterInvitationService.revoke_invite_code(code_id)
    if not success:
        return get_json_result(
            data=False,
            message="Failed to revoke invite code",
            code=500
        )
    
    return get_json_result(data=True)

@manager.route("/invite-codes/list", methods=["POST"])
@login_required
def get_invite_codes():
    """获取邀请码列表（纯POST方式）"""
    data = request.json
    page = data.get("page", 1)
    per_page = data.get("per_page", 10)
    
    result = RegisterInvitationService.get_invite_codes(page, per_page)
    return get_json_result(data=result)